package com.znjc.device.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.znjc.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * 自动填充实现类
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /*mybatis-plus实现添加操作*/
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("mybatis plus start insert fill ....");
        Date now = new Date();
        fillValIfNullByName("createTime", now, metaObject, false);
        fillValIfNullByName("delFlag", "0", metaObject, false);
        fillValIfNullByName("status", "0", metaObject, false);
        if (verifyValue("createBy", metaObject)) {
            fillValIfNullByName("createBy", SecurityUtils.getUsername(), metaObject, false);
        }
        if (verifyValue("deptId", metaObject)) {
            fillValIfNullByName("deptId", SecurityUtils.getDeptId(), metaObject, false);
        }

    }

    /*mybatis-plus实现更新操作*/
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("mybatis plus start update fill ....");
        fillValIfNullByName("updateTime", new Date(), metaObject, true);
        if (verifyValue("updateBy", metaObject)) {
            fillValIfNullByName("updateBy", SecurityUtils.getUsername(), metaObject, true);
        }
    }

    /**
     * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
     *
     * @param fieldName  属性名
     * @param fieldVal   属性值
     * @param metaObject MetaObject
     * @param isCover    是否覆盖原有值,避免更新操作手动入参
     */
    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
        // 1. 没有 set 方法
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 2. 如果用户有手动设置的值
        Object userSetValue = metaObject.getValue(fieldName);
        String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (StrUtil.isNotBlank(setValueStr) && !isCover) {
            return;
        }
        // 3. field 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

    /**
     * 判断是否存在值
     *
     * @param name
     * @param metaObject
     * @return
     */
    private static Boolean verifyValue(String name, MetaObject metaObject) {
        Object userSetValue = metaObject.getValue(name);
        String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (StrUtil.isNotBlank(setValueStr)) {
            return false;
        } else {
            return true;
        }
    }

}


